using UnityEngine;
using System.Collections;

public class CharacterManager: MonoBehaviour {
	
	public Transform[] spawns;
	public GameObject gun;
	
	public int playerLives = 3;
	public int score = 0;
	
	public GameObject text;
	const float textDelay = 2f;
	
	float lastFloatDisplaySec = 0;
	string lastMessage;
	public bool dead;
	
	public AudioClip death;
	
	// Use this for initialization
	void Start () {
	
	}
	
	// Update is called once per frame
	void Update () {
		
	}
	
	/*
	 * Handles score incrementing.
	 */
	public void incrementScore( int amt ) {
		this.score += amt;
		
		if (amt > 0)
			floatMessage( "+ " + amt, Color.cyan );
		else
			floatMessage( "" + amt, Color.red );
	}
	
	/**
	 * Creates text at the player's current positoin.
	 */
	public void floatMessage( string message, Color color ) {
		// track times to avoid painting with text
		if (message.Equals ( lastMessage ) && lastFloatDisplaySec + (textDelay * 0.5f) > Time.timeSinceLevelLoad) {
			return;
		}
		lastFloatDisplaySec = Time.timeSinceLevelLoad;
		lastMessage = message;
		
		Vector3 curPlayer = this.gameObject.transform.position;
		
		GameObject made = (GameObject) Instantiate( text, curPlayer, Quaternion.identity );
		
		made.GetComponent<TextMesh>().text = message;
		made.GetComponent<TextMesh>().renderer.material.color = color;
		
		made.GetComponent<DestroyAfter>().killAtTime = Time.timeSinceLevelLoad + textDelay;
	}
	
	/**
	 * Handles player live subtract, end game check, and player respawn.
	 */
	public void respawn() {
		this.playerLives--;
		StartCoroutine(playSound(death));
		gun.gameObject.GetComponent<bulletFlightPath>().clipContents = gun.gameObject.GetComponent<bulletFlightPath>().clipSize;
		gun.gameObject.GetComponent<bulletFlightPath>().outOfAmmo = false;
		if (playerLives == 0) {
			dead= true;
		}
		
		// respawn enemies
		for (int i=0; i < GenerateObjects.originalLocations.Count; i++) {
			GameObject amIDead = (GameObject) GenerateObjects.everyEnemy[i];
			if (amIDead == null) {
				Vector3 spawnHere = (Vector3) GenerateObjects.originalLocations[i];
				if ("EnemyOne".Equals ( GenerateObjects.originalTags[i] ) ) {
					GenerateObjects.cheatMakeEnemyOne( spawnHere );
				}
				else {
					GenerateObjects.cheatMakeEnemyTwo( spawnHere );
				}
			}
		}
			
		bool found = false;
		for(int i = spawns.Length-1; i > 0;i--){
			if (this.gameObject.transform.position.x > spawns[i].position.x){
				this.gameObject.transform.position = spawns[i].position;
				this.gameObject.rigidbody.velocity = Vector3.zero;
				found = true;
				break;
			}	
		}
		
		if (!found)
			this.gameObject.transform.position = spawns[0].position;
		
		// tell player
		floatMessage( "\u2620 -1 Life \u2620", Color.red );
	}
	public IEnumerator playSound(AudioClip a){
		audio.clip = a;
		audio.Play();
		Debug.Log(a.name);
		yield return new WaitForSeconds(1);
		
	}
	
	public void Restart() {
		playerLives= 4;
		respawn();
	}
}
